// 管理用户数据

import { ref } from 'vue'
import { defineStore } from 'pinia'
import { getUserInfoAPI } from '@/apis/user';
import { ElMessage } from 'element-plus';

export const useUserStore = defineStore('user', () => {
    // 保存用户信息
    const userInfo = ref({
        "id": -1,
        "account": "",
        "username": "",
        "avatarUrl": "",
        "token": "",
        "role": ""
    })

    const getUserInfo = async () => {
        try {
            const res = await getUserInfoAPI()
            if (res.code === 0) {
                // 请求成功
                userInfo.value.id = res.user.id
                userInfo.value.account = res.user.account
                userInfo.value.username = res.user.username
                userInfo.value.avatarUrl = res.user.avatar_url
                userInfo.value.role = res.user.role
            }
            return { "code": res.code, "message": res.message }
        } catch {
            // 请求失败
            ElMessage({ type: "error", message: "获取用户信息失败" })
        }
    }

    const clearUserInfo = () => {
        userInfo.value = {
            "id": -1,
            "account": "",
            "username": "",
            "avatarUrl": "",
            "token": "",
            "role": ""
        }
    }

    return { userInfo, getUserInfo, clearUserInfo };
}, {
    persist: true
})
